<template>
	<view class="page">
		<cu-custom :isBack="true" class="bg-blue" :backPress="clickBack">
			<block slot="backText">返回</block>
			<block slot="content">{{mobile.projectName}}</block>
			<block slot="right">
				<view class="action">
					<view class="cuIcon cuIcon-location" @tap="clickLocation"></view>
				</view>
			</block>
		</cu-custom>
		<view class="container" style="height: 0;flex-grow: 1;">
			<view class="container_body" style="height: 0;flex-grow: 1;position: relative;">
				<!-- 第二层  -->
				<view class="container_target">
					<view class="cu-list grid col-2">
						<view class="cu-item no-border" :key="index" v-for="(item,index) in mobile.items" :data-index="index" @tap="clickTargetItem">
							<view class="cu-item_card">
								<view class="cu-item_card_image">
									<image :src="baseUrl+'mcs'+item.imgUri"  mode="widthFix" class="response"></image>
								</view>
								<view class="text-bold text-black" style="margin-top: 5px;">
									{{item.name}}
								</view>
								<view class="cu-item_card_badge bg-red text-white" v-if="item.dangerCount && item.dangerCount>0">
									{{item.dangerCount}}
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 第三层巡检点 -->
				<view class="container_point" v-if="currentTarget">
					<view class="container_point_card bg-white shadow" :key="index" v-for="(item,index) in currentTarget.items" @tap="clickPointItem"
					 :data-index="index">
						<view class="cf padding-xs">
							<view class="fl">
								巡查项
							</view>
							<view class="fr text-red" v-if="item.dangerCount && item.dangerCount>0">
								{{item.dangerCount}}条隐患
							</view>
							<view class="fr text-green" v-else>
								正常
							</view>
						</view>
						<view class="text-black text-bold padding-xs">
							{{item.title}}
						</view>

						<view class="text-gray padding-xs">
							{{item.name}}
						</view>

						<view class="text-red padding-xs" v-if="item.defectContentDesc">
							日常跟踪：上次该处出现异常，异常描述为【{{item.defectContentDesc}}】
						</view>
					</view>
				</view>
			</view>
			<!-- 提交按钮 -->
			<view class="submit flex padding bg-white align-center shadow">
				<view class="flex-sub cu-list text-lg">
					<view class="cu-item">
						<i class="cuIcon cuIcon-time text-black"></i>
						巡查时间
						<span class="text-red">{{record.patrolTime | formatTime}}</span>
					</view>

					<view class="cu-item margin-top">
						<i class="cuIcon cuIcon-footprint text-black"></i>
						巡查距离
						<span class="text-red">{{record.patrolLength}}</span>
						<span class="text-gray">米</span>
					</view>
				</view>
				<button class="cu-btn lg bg-blue round" @tap="clickSubmit">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		uuid
	} from 'vue-uuid';
	import {
		mapGetters
	} from 'vuex'
	import patrolUtil from '../../util/patrolUtil.js'
	import constant from '../../util/constant.js'

	let that = null;
	export default {
		filters: {
			formatTime: function(seconds) {
				// 处理时间 格式  时分秒
				let startHours = parseInt(seconds / 3600);
				let startMinutes = parseInt((seconds % 3600) / 60);
				let startSeconds = parseInt((seconds % 3600) % 60);
				let timeStr = (startHours < 10 ? ('0' + startHours) : startHours) + "时" + (startMinutes < 10 ? ('0' + startMinutes) :
					startMinutes) + "分" + (startSeconds < 10 ? ('0' + startSeconds) : startSeconds) + "秒";
				return timeStr
			}
		},
		data() {
			return {
				baseUrl:constant.baseUrl,
				// 定时定位的timmer
				timmer: null,
				// 定时刷新时间的timmer
				timmerTime: null,
				// 原始数据
				mobile: {},
				// 要提交的数据
				record: {},
				// 坐标点集合
				points: [],
				// 当前点击的target
				currentTarget: null,
				// 当前点击的point
				currentPoint: null
			}
		},
		computed: {
			...mapGetters(['userInfo'])
		},
		onLoad(options) {
			that = this;
			let mobile = JSON.parse(decodeURIComponent(options.mobile))
			that.mobile = mobile;
			// 初始化record数据
			// metadata info
			that.record.createEmployeeId = that.userInfo.userId;
			that.record.createEmployeeName = that.userInfo.name;
			that.record.createDate = new Date().getTime();
			that.record.editEmployeeId = that.mobile.editEmployeeId;
			that.record.editEmployeeName = that.mobile.editEmployeeName;
			that.record.editDate = that.mobile.editDate;
			that.record.deleteEmployeeId = that.mobile.deleteEmployeeId;
			that.record.deleteEmployeeName = that.mobile.deleteEmployeeName;
			that.record.deleteDate = that.mobile.deleteDate;
			that.record.deleteFlag = that.mobile.deleteFlag;
			// 巡检数据
			that.record.mobileCheckId = that.mobile.id;
			that.record.mobileCheckName = that.mobile.projectName;
			that.record.patrolCoors = '';
			that.record.patrolLength = 0;
			that.record.patrolTime = 0;
			that.record.patrolStartTime = new Date().getTime();
			that.record.patrolEmployeeId = that.userInfo.userId;
			that.record.patrolEmployeeName = that.userInfo.name;
			that.record.hasReport = 0;
			that.record.items = [];
			// 遍历mobile中的items
			{
				let targetList = that.mobile.items;
				for (let i = 0; i < targetList.length; i++) {
					let target = targetList[i];
					let contentList = target.items;
					for (let j = 0; j < contentList.length; j++) {
						let content = contentList[j];
						let danger = {};
						danger.mobileCheckRecordId = that.mobile.id;
						danger.patrolParentId = target.id;
						danger.patrolParentTitle = target.title;
						danger.patrolParentName = target.name;
						danger.patrolIndexId = content.id;
						danger.patrolIndexTitle = content.title;
						danger.patrolIndexName = content.name;
						danger.hasError = 0;
						danger.dangerId = uuid.v4();
						danger.dangerDesc = '';
						danger.attachmentLocalList = [];
						danger.dangerLat = 0.0;
						danger.dangerLng = 0.0;
						danger.id = 0;
						that.record.items.push(danger);
					}
				}
			}
			// 开始定位
			that.startLocation();

			// 注册
			uni.$on('updateMobileDanger', danger => {
				// 添加该danger的位置信息
				if (that.points.length > 0) {
					let lastP = that.points[that.points.length - 1];
					danger.dangerLat = lastP.latitude;
					danger.dangerLng = lastP.longitude;
				}
				// 找到record中的danger并删除  添加此danger
				that.record.items.splice(that.findDangerIndexInRecord(danger.patrolIndexId), 1);
				that.record.items.push(danger);
				// 更新target 和 points中的errorCount
				that.updateTargetErrorCount();
				that.updatePointErrorCount();
				// 强行刷新
				that.$forceUpdate();
			})
			// 定时刷新时间
			that.timmerTime = setInterval(() => {
				// let time = that.record.patrolTime;
				// time++;
				// that.$set(that.record, 'patrolTime', time);
				that.record.patrolTime += 1;
				that.$forceUpdate()
			}, 1000)
		},
		onBackPress(event) {
			if (event.from == 'backbutton') {
				that.clickBack();
				return true;
			} else {
				return false;
			}
		},
		onReady() {

		},
		onShow() {},
		onUnload() {
			// 注销定位的timmer
			clearTimeout(that.timmer);
			// 注销时间的timmer
			clearInterval(that.timmerTime)
			// 注销
			uni.$off('updateMobileDanger');
		},
		methods: {
			// ————————————————————————————————点击事件————————————————————————————————————
			/**
			 * 点击跳转到地图页面
			 */
			clickLocation: function() {
				let pointsJSON = encodeURIComponent(JSON.stringify(that.points));
				uni.navigateTo({
					url: './patrol_mobile_map?points=' + pointsJSON
				})
			},
			/**
			 * 点击返回时的事件
			 */
			clickBack: function() {
				// 首先判断是否是target页面
				if (that.currentTarget == null) {
					uni.showModal({
						title: "提示",
						content: "正在巡检中，是否终止巡检？",
						cancelText: "取消",
						cancelColor: "#737373",
						confirmText: "终止",
						confirmColor: "#E64340",
						success(res) {
							if (res.confirm) {
								uni.navigateBack()
							}
						}
					})
				} else {
					that.currentTarget = null;
				}
			},
			/**
			 * 点击target 列表时的点击事件
			 */
			clickTargetItem: function(e) {
				let index = e.currentTarget.dataset.index;
				let target = that.mobile.items[index];
				that.currentTarget = target;
			},
			/**
			 * 点击points列表时的点击事件
			 * @param {Object} e
			 */
			clickPointItem: function(e) {
				let index = e.currentTarget.dataset.index;
				let point = that.currentTarget.items[index];
				that.currentPoint = point;
				// 找到record中的danger
				let danger = that.findDangerInRecord(point.id);
				if (danger == null) {
					return;
				}
				// 跳转到添加隐患的页面
				uni.navigateTo({
					url: './patrol_mobile_danger_add?danger=' + encodeURIComponent(JSON.stringify(danger))
				})
			},
			/**
			 * 点击提交巡检数据
			 */
			clickSubmit: function() {
				uni.showModal({
					title: '上传',
					content: '确定上传本次巡检数据？',
					cancelText: '取消',
					confirmText: '确定',
					success(res) {
						if (res.confirm) {
							// 完成结束的数据
							let date = new Date();
							that.record.patrolEndTime = date.getTime();
							that.record.patrolSubmitTime = date.getTime();
							that.record.errorCount = that.findRecordErrorCount();
							// 坐标点
							that.record.patrolCoors = patrolUtil.latlngListToString(that.points);
							// 提交数据
							console.log(that.record);
							patrolUtil.uploadMobileRecord(that.record, res => {
								uni.showModal({
									title:"成功",
									content:"巡检记录上传成功!",
									showCancel:false,
									confirmText:'确定',
									success(res) {
										if(res.confirm){
											uni.navigateBack()
										}
									}
								})
							})
						}
					}
				})
			},

			// ————————————————————————————————其他方法————————————————————————————————————
			/**
			 * 开始定位
			 */
			startLocation: function() {
				that.timmer = setTimeout(function() {
					uni.getLocation({
						type: 'gcj02', //使用高德地图的坐标系
						success(res) {
							// {
							// 	"type": "GCJ02",
							// 	"altitude": 0,
							// 	"latitude": 31.276591,
							// 	"longitude": 120.53878,
							// 	"speed": 0,
							// 	"accuracy": 68,
							// 	"errMsg": "getLocation:ok"
							// }
							// 当前点
							let p = {
								longitude: res.longitude,
								latitude: res.latitude
							};
							if (that.points.length == 0) {
								// 直接加入
								console.log('坐标点第一次加入集合')
								that.points.push(p);
								// 更新地图点位
								uni.$emit("updatePoints", that.points)
							} else {
								// 取最后一个点
								let l = that.points[that.points.length - 1];
								// 计算距离
								let currP = new plus.maps.Point(p.longitude, p.latitude);
								let lastP = new plus.maps.Point(l.longitude, l.latitude);
								plus.maps.Map.calculateDistance(currP, lastP, event => {
									let distance = event.distance;
									if (distance >= 10) {
										// 距离够了，可以加入集合中
										console.log('坐标点距离满足，加入集合，距离为>>>>>' + distance)
										that.points.push(p);
										// 更新距离
										that.record.patrolLength += parseInt(distance);
										// 更新地图点位
										uni.$emit("updatePoints", that.points)
									} else {
										console.log('坐标点距离不够，不加入集合中，距离为>>>>>' + distance);
									}
								})
							}

						},
						fail() {

						},
						complete() {
							// 继续定位
							that.startLocation()
						}
					})
				}, 5000)
			},
			/**
			 * 根据pointid 在record列表中寻找到danger
			 * @param {Object} pointId
			 */
			findDangerInRecord: function(pointId) {
				let items = that.record.items;
				for (let i = 0; i < items.length; i++) {
					let danger = items[i];
					if (danger.patrolIndexId == pointId) {
						return danger;
					}
				}
				return null;
			},
			/**
			 * 根据pointId找到record中的index
			 * @param {Object} pointId
			 */
			findDangerIndexInRecord: function(pointId) {
				let items = that.record.items;
				for (let i = 0; i < items.length; i++) {
					let danger = items[i];
					if (danger.patrolIndexId == pointId) {
						return i;
					}
				}
				return -1;
			},
			/**
			 * 更新target中的errorCount
			 */
			updateTargetErrorCount: function() {
				let targetList = that.mobile.items;
				for (let i = 0; i < targetList.length; i++) {
					let target = targetList[i];
					let num = 0;
					for (let j = 0; j < that.record.items.length; j++) {
						let danger = that.record.items[j];
						if (danger.patrolParentId == target.id && danger.hasError == 1) {
							num++;
						}
					}
					target.dangerCount = num;
				}
			},
			/**
			 * 更新point中的errorCount
			 */
			updatePointErrorCount: function() {
				let targetList = that.mobile.items;
				for (let i = 0; i < targetList.length; i++) {
					let target = targetList[i];
					for (let j = 0; j < target.items.length; j++) {
						let point = target.items[j];
						let num = 0;
						for (let k = 0; k < that.record.items.length; k++) {
							let danger = that.record.items[k];
							if (danger.patrolIndexId == point.id && danger.hasError == 1) {
								num++;
							}
						}
						point.dangerCount = num;
					}
				}
			},
			/**
			 * 找出err数量
			 */
			findRecordErrorCount: function() {
				let count = 0;
				for (let i = 0; i < that.record.items.length; i++) {
					let danger = that.record.items[i];
					if (danger.hasError == 1) {
						count++;
					}
				}
				return count;
			},
			// ————————————————————————————————api方法————————————————————————————————————
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
	}


	.container_target,
	.container_point {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		overflow: auto;
	}

	.container_target {}

	.cu-item_card {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
	}

	.cu-item_card_badge {
		position: absolute;
		right: 10px;
		top: 0px;
		width: 20px;
		height: 20px;
		line-height: 20px;
		text-align: center;
		border-radius: 50%;
	}

	.cu-item_card_image {
		width: 120px;
		height: 120px;
		background-size: cover;
		background-image: url('../../static/patrol/patrol_mobile_device_default_image.webp');
	}

	.container_point {
		background-color: #F1F1F1;
	}

	.container_point_card {
		margin: 10px;
		background-color: white;
		border-radius: 5px;
		padding: 10px;
		overflow: hidden;
	}

	.container .submit {}

	.container .submit button {
		width: 100px;
	}
</style>
